<template>
  <div class="create-batch-container">
    <el-container class="layout-container">
      <el-aside width="220px" class="sidebar">
        <div class="sidebar-content">
          <el-button @click="goBack" class="back-btn">
            <el-icon><ArrowLeft /></el-icon>
            返回主页
          </el-button>
        </div>
      </el-aside>

      <el-main class="main-content">
        <div class="page-header">
          <h1>{{ isUpdate ? '更新产品批号' : '创建产品批号' }}</h1>
          <p>{{ isUpdate ? '更新产品批号信息' : '请填写产品批号相关信息' }}</p>
        </div>

        <!-- 新建/更新产品批号表单 -->
        <el-card class="form-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><DocumentAdd /></el-icon>
              <span>{{ isUpdate ? '更新产品批号' : '新建产品批号' }}</span>
            </div>
          </template>

          <el-form
            :model="batchForm"
            :rules="batchRules"
            ref="batchFormRef"
            label-width="200px"
            class="batch-form"
            v-loading="loading"
          >
            <!-- 1. 产品批号 -->
            <el-form-item label="产品批号：" prop="batchId">
              <el-input
                v-model="batchForm.batchId"
                :disabled="isUpdate"
                placeholder="请输入产品批号"
                @blur="checkBatchId"
                :class="{ 'error-border': batchIdExists }"
                class="form-input"
              />
              <div v-if="batchIdExists" class="error-text">
                <el-icon><Warning /></el-icon>
                该产品批号已存在
              </div>
            </el-form-item>

            <!-- 2. 屠宰企业所在省 -->
            <el-form-item label="屠宰企业所在省：" prop="provId">
              <el-select
                v-model="batchForm.provId"
                placeholder="请选择省份"
                @change="handleProvinceChange"
                class="form-input"
              >
                <el-option
                  v-for="prov in provinces"
                  :key="prov.provId || prov.nodeId"
                  :label="prov.provName"
                  :value="prov.provId || prov.nodeId"
                />
              </el-select>
            </el-form-item>

            <!-- 3. 屠宰企业所在市 -->
            <el-form-item label="屠宰企业所在市：" prop="cityId">
              <el-select
                v-model="batchForm.cityId"
                placeholder="请选择城市"
                @change="handleCityChange"
                :disabled="!batchForm.provId"
                class="form-input"
              >
                <el-option
                  v-for="city in cities"
                  :key="city.cityId || city.nodeId"
                  :label="city.cityName"
                  :value="city.cityId || city.nodeId"
                />
              </el-select>
            </el-form-item>

            <!-- 4. 屠宰企业名称 -->
            <el-form-item label="屠宰企业名称：" prop="slauId">
              <el-select
                v-model="batchForm.slauId"
                placeholder="请选择屠宰企业"
                @change="handleSlauChange"
                :disabled="!batchForm.cityId"
                class="form-input"
              >
                <el-option
                  v-for="ent in slaughterEnts"
                  :key="ent.nodeId"
                  :label="ent.name"
                  :value="ent.nodeId"
                />
              </el-select>
            </el-form-item>

            <!-- 5. 屠宰企业产品批号 -->
            <el-form-item label="屠宰企业产品批号：" prop="slauBatchId">
              <el-select
                v-model="batchForm.slauBatchId"
                placeholder="请选择产品批号"
                @change="handleSlauBatchChange"
                :disabled="!batchForm.slauId"
                class="form-input"
              >
                <el-option
                  v-for="batch in slauBatches"
                  :key="batch.sbId"
                  :label="batch.batchId"
                  :value="batch.sbId"
                />
              </el-select>
            </el-form-item>

            <!-- 6. 屠宰企业产品品种 -->
            <el-form-item label="屠宰企业产品品种：" prop="productVariety">
              <el-input
                v-model="batchForm.productVariety"
                disabled
                class="form-input"
              />
            </el-form-item>

            <!-- 7. 产品类型 -->
            <el-form-item label="产品类型：" prop="productType">
              <el-select
                v-model="batchForm.productType"
                placeholder="请选择产品类型"
                class="form-input"
              >
                <el-option label="冷鲜肉" value="冷鲜肉" />
                <el-option label="冻肉" value="冻肉" />
                <el-option label="肉制品" value="肉制品" />
              </el-select>
            </el-form-item>

            <!-- 8. 是否向上游企业发送确认请求（仅更新时显示） -->
            <el-form-item v-if="isUpdate" label="发送确认请求：" prop="sendConfirm">
              <el-checkbox v-model="sendConfirm">
                是否向上游企业发送确认请求
              </el-checkbox>
            </el-form-item>

            <!-- 9. 操作按钮 -->
            <el-form-item class="form-actions">
              <el-button
                type="primary"
                @click="submitForm"
                :loading="loading"
                class="submit-btn"
              >
                <el-icon><Check /></el-icon>
                {{ isUpdate ? '更新产品批号' : '新建产品批号' }}
              </el-button>
              <el-button @click="resetForm" class="reset-btn">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
              <el-button @click="goBack" class="cancel-btn">
                <el-icon><Close /></el-icon>
                取消
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  DocumentAdd,
  Warning,
  Loading,
  Check,
  Refresh,
  Close
} from '@element-plus/icons-vue'
import { 
  getProvincesService, 
  getCitiesService,
  getSlaughterEntsService,
  getSlauBatchesService,
  getWholBatchDetailService,
  updateWholBatchService,
  createWholBatchService,
  checkWholBatchIdExistsService
} from '@/api/wholesaler'

const router = useRouter()
const route = useRoute()
const batchFormRef = ref(null)
const wbId = route.params.id

// 判断是否为更新页面
const isUpdate = computed(() => !!wbId)

// 表单数据
const batchForm = ref({
  wbId: '',
  batchId: '',
  provId: '',
  cityId: '',
  slauId: '',
  slauBatchId: '',
  productVariety: '',
  productType: '',
  type: '' // 用于存储产品类型，与后端字段对应
})

// 发送确认请求标记
const sendConfirm = ref(false)

// 批号是否存在标记
const batchIdExists = ref(false)

// 加载状态
const loading = ref(false)

// 验证规则
const batchRules = {
  batchId: [
    { required: true, message: '请输入产品批号', trigger: 'blur' }
  ],
  provId: [
    { required: true, message: '请选择省份', trigger: 'change' }
  ],
  cityId: [
    { required: true, message: '请选择城市', trigger: 'change' }
  ],
  slauId: [
    { required: true, message: '请选择屠宰企业', trigger: 'change' }
  ],
  slauBatchId: [
    { required: true, message: '请选择产品批号', trigger: 'change' }
  ],
  productType: [
    { required: true, message: '请选择产品类型', trigger: 'change' }
  ]
}

// 联动数据
const provinces = ref([])
const cities = ref([])
const slaughterEnts = ref([])
const slauBatches = ref([])

// 返回主页
const goBack = () => {
  router.push('/ent/farm')
}

// 加载省份数据
const loadProvinces = async () => {
  loading.value = true
  try {
    console.log('开始加载省份数据...')
    const res = await getProvincesService()
    console.log('省份数据响应:', res)
    if (res.code === 0) {
      provinces.value = res.data || []
      console.log('成功加载省份数据:', provinces.value)
    } else {
      throw new Error(res.message || '获取省份数据失败')
    }
  } catch (error) {
    console.error('加载省份数据失败:', error)
    ElMessage.error('加载省份数据失败: ' + (error.message || error.data?.message || '未知错误'))
    provinces.value = []
  } finally {
    loading.value = false
  }
}

// 加载当前批号详情
const loadBatchDetail = async () => {
  if (!isUpdate.value || !wbId) return
  
  loading.value = true
  try {
    const res = await getWholBatchDetailService(wbId)
    batchForm.value = {
      ...res.data,
      productType: res.data.type // 将后端的type字段映射到前端的productType
    }
    // 初始化联动数据
    if (batchForm.value.provId) {
      handleProvinceChange(batchForm.value.provId)
      setTimeout(() => {
        if (batchForm.value.cityId) {
          handleCityChange(batchForm.value.cityId)
          setTimeout(() => {
            if (batchForm.value.slauId) {
              handleSlauChange(batchForm.value.slauId)
            }
          }, 300)
        }
      }, 300)
    }
  } catch (error) {
    ElMessage.error('加载批号详情失败: ' + (error.message || '未知错误'))
    batchForm.value = {
      wbId: '',
      batchId: '',
      provId: '',
      cityId: '',
      slauId: '',
      slauBatchId: '',
      productVariety: '',
      productType: '',
      type: ''
    }
  } finally {
    loading.value = false
  }
}

// 检查批号是否存在
const checkBatchId = async () => {
  if (!batchForm.value.batchId) {
    batchIdExists.value = false
    return
  }
  
  try {
    const res = await checkWholBatchIdExistsService(batchForm.value.batchId)
    batchIdExists.value = res.data || false
  } catch (error) {
    ElMessage.error('检查批号失败: ' + (error.message || '未知错误'))
    batchIdExists.value = false
  }
}

// 省份变化处理
const handleProvinceChange = async (provId) => {
  console.log('省份变化，选中的provId:', provId)
  batchForm.value.cityId = ''
  batchForm.value.slauId = ''
  batchForm.value.slauBatchId = ''
  cities.value = []
  slaughterEnts.value = []
  slauBatches.value = []
  
  if (!provId) return
  
  loading.value = true
  try {
    console.log('开始加载城市数据，provId:', provId)
    const res = await getCitiesService(provId)
    console.log('城市数据响应:', res)
    if (res.code === 0) {
      cities.value = res.data || []
      console.log('成功加载城市数据:', cities.value)
    } else {
      throw new Error(res.message || '获取城市数据失败')
    }
  } catch (error) {
    console.error('加载城市数据失败:', error)
    ElMessage.error('加载城市数据失败: ' + (error.message || error.data?.message || '未知错误'))
    cities.value = []
  } finally {
    loading.value = false
  }
}

// 城市变化处理
const handleCityChange = async (cityId) => {
  console.log('城市变化，选中的cityId:', cityId)
  batchForm.value.slauId = ''
  batchForm.value.slauBatchId = ''
  slaughterEnts.value = []
  slauBatches.value = []
  
  if (!cityId) return
  
  loading.value = true
  try {
    console.log('开始加载屠宰企业数据，provId:', batchForm.value.provId, 'cityId:', cityId)
    const res = await getSlaughterEntsService({
      provId: batchForm.value.provId,
      cityId
    })
    console.log('屠宰企业数据响应:', res)
    if (res.code === 0) {
      slaughterEnts.value = res.data || []
      console.log('成功加载屠宰企业数据:', slaughterEnts.value)
    } else {
      throw new Error(res.message || '获取屠宰企业数据失败')
    }
  } catch (error) {
    console.error('加载屠宰企业数据失败:', error)
    ElMessage.error('加载屠宰企业数据失败: ' + (error.message || error.data?.message || '未知错误'))
    slaughterEnts.value = []
  } finally {
    loading.value = false
  }
}

// 屠宰企业变化处理
const handleSlauChange = async (slauId) => {
  console.log('屠宰企业变化，选中的slauId:', slauId)
  batchForm.value.slauBatchId = ''
  slauBatches.value = []
  
  if (!slauId) return
  
  loading.value = true
  try {
    console.log('开始加载产品批号数据，slauId:', slauId)
    const res = await getSlauBatchesService(slauId)
    console.log('产品批号数据响应:', res)
    if (res.code === 0) {
      slauBatches.value = res.data || []
      console.log('成功加载产品批号数据:', slauBatches.value)
    } else {
      throw new Error(res.message || '获取产品批号数据失败')
    }
  } catch (error) {
    console.error('加载产品批号数据失败:', error)
    ElMessage.error('加载产品批号数据失败: ' + (error.message || error.data?.message || '未知错误'))
    slauBatches.value = []
  } finally {
    loading.value = false
  }
}

// 批号变化处理
const handleSlauBatchChange = (batchId) => {
  const selectedBatch = slauBatches.value.find(b => b.sbId === batchId)
  if (selectedBatch) {
    batchForm.value.productVariety = selectedBatch.type
    batchForm.value.type = selectedBatch.type // 同步设置type字段
  }
}

// 提交表单
const submitForm = async () => {
  if (!batchFormRef.value) return

  try {
    const valid = await batchFormRef.value.validate()
    if (!valid) {
      ElMessage.error("请完善表单信息")
      return
    }

    // 如果是创建模式且批号已存在，提示用户确认
    if (!isUpdate.value && batchIdExists.value) {
      try {
        await ElMessageBox.confirm('该产品批号已存在，是否继续创建？', '确认提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch {
        return // 用户取消操作
      }
    }
    
    loading.value = true

    // 构造提交数据
    const submitData = {
      ...batchForm.value,
      type: batchForm.value.productType // 将前端的productType映射到后端的type字段
    }
    
    if (isUpdate.value) {
      // 更新操作
      const params = {
        ...submitData,
        // 若发送确认请求，更新状态为待确认(2)
        state: sendConfirm.value ? 2 : submitData.state
      }
      await updateWholBatchService(params)
      ElMessage.success('更新成功')
    } else {
      // 创建操作
      await createWholBatchService(submitData)
      ElMessage.success('创建成功')
    }
    goBack()
  } catch (error) {
    ElMessage.error((isUpdate.value ? '更新失败: ' : '创建失败: ') + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (batchFormRef.value) {
    batchFormRef.value.resetFields()
  }
  batchIdExists.value = false
  sendConfirm.value = false
}

// 初始化
onMounted(() => {
  loadProvinces()
  loadBatchDetail()
})
</script>

<style scoped>
.create-batch-container {
  height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

.layout-container {
  height: 100%;
}

.sidebar {
  background: linear-gradient(180deg, #2d3748 0%, #1a202c 100%);
  padding: 20px;
  display: flex;
  align-items: flex-start;
}

.sidebar-content {
  width: 100%;
}

.back-btn {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
}

.back-btn .el-icon {
  margin-right: 8px;
}

.main-content {
  padding: 30px;
  background: transparent;
  overflow-y: auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #2d3748;
  font-size: 28px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #718096;
  font-size: 16px;
}

.form-card {
  max-width: 800px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 0.95);
}

.card-header {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
}

.card-header .el-icon {
  margin-right: 8px;
  color: #409eff;
}

.batch-form {
  padding: 10px 0;
}

.form-input {
  width: 300px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #4a5568;
}

.form-actions {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e2e8f0;
}

.submit-btn,
.reset-btn,
.cancel-btn {
  border-radius: 8px;
  height: 40px;
  padding: 0 20px;
  transition: all 0.3s ease;
}

.submit-btn {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.reset-btn:hover,
.cancel-btn:hover {
  transform: translateY(-1px);
}

.submit-btn .el-icon,
.reset-btn .el-icon,
.cancel-btn .el-icon {
  margin-right: 6px;
}

.error-border {
  border-color: #f56565;
}

.error-text {
  color: #f56565;
  font-size: 12px;
  margin-top: 5px;
  display: flex;
  align-items: center;
}

.error-text .el-icon {
  margin-right: 4px;
  font-size: 14px;
}

.loading-text {
  color: #4299e1;
  font-size: 12px;
  margin-top: 5px;
  display: flex;
  align-items: center;
}

.loading-text .el-icon {
  margin-right: 4px;
  font-size: 14px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@media (max-width: 768px) {
  .sidebar {
    width: 100% !important;
    height: auto;
  }

  .main-content {
    padding: 20px;
  }

  .page-header h1 {
    font-size: 24px;
  }

  .form-input {
    width: 100%;
  }

  :deep(.el-form-item__label) {
    width: 100% !important;
  }
}
</style>